<!-- 聊天备份 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff; padding: 10px ;">
      <div style="display:flex;">
        <div class="lefttree" style="height:calc(100vh - 96px);">
          <div class="tabclick">
          </div>
          <el-tree ref="tree" v-show="tab1" node-key="label" :data="CustomerList" :expand-on-click-node=false
            :props="defaultProps" @node-click="handleNodeClick" default-expand-all :default-expanded-keys="[1]"
            highlight-current style="width:200px;">
            <span slot-scope="{ node }" class="custom-tree-node">
              <span>
                <i v-if="node.level > 2" class="el-icon-picture" style="margin-right: 10px;" />
                <i v-else class="el-icon-folder-opened" style="margin-right: 10px;" />
                <span class="tree-text">{{ node.label }}{{ node.Count }}</span>
              </span>
            </span>
          </el-tree>
        </div>
        <div style="width:100%">
          <div class="playbackSettings"
            style="display:flex;justify-content: space-between;align-items: center;height: 60px;">
            <div style="font-size:14px;color:#606266;display:flex;align-items: center;">
              自动播放时间间隔：<el-input v-model.number="time" @change="timeChange" @input="time = $event.replace(/[^0-9]/g, '')"
                style="width:100px" maxlength="2"></el-input>秒
              <el-tooltip class="item" effect="dark" content="自动播放" placement="top">
                <el-image @click="autoPlay"
                  style="width: 30px; height: 30px;cursor: pointer;margin-right:20px;margin-left:20px;"
                  :src="require('@/assets/zdbf@2x.png')" fit="fit"></el-image>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="停止播放" placement="top">
                <el-image @click="stopPlaying" style="width: 30px; height: 30px;cursor: pointer;margin-right:20px;"
                  :src="require('@/assets/ztbf@2x.png')" fit="fit"></el-image>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content="全屏自动播放" placement="top">
                <el-image @click="fullScreenAutoPlay" style="width: 30px; height: 30px;cursor: pointer;margin-right:20px;"
                  :src="require('@/assets/qpbf@2x.png')" fit="fit"></el-image>
              </el-tooltip>
              <el-checkbox v-model="intelligentDeduplication" :true-label="1" :false-label="0"
                @change="GetScreenLog(intelligentDeduplication)">智能去重</el-checkbox>
            </div>
            <el-button type="primary" @click="goback()">返回</el-button>
          </div>
          <div ref="imageContainer" class="image-container">
            <div v-if="isFullscreen" class="fullscreen-info">
              <span>{{ currentNodeLabel }}</span>
              <span>{{ currentProgress }}</span>
            </div>
            <el-image v-for="(item, index) in filteredTableData" :key="index" ref="image" :src="item.ResFileName"
              :preview-src-list="isFullscreen ? [] : previewSrcList" :data-index="item.TransTime"></el-image>
          </div>
        </div>
      </div>
    </el-row>
  </div>
</template>

<script>
import { parseTime } from '@/utils/index.js';
import { connrequest } from '@/api/firstPage.js';
import connsearch from "@/components/connSearch";
import barchart from "./components/barchart.vue";
import piechart from "./components/piechart.vue";
let timer
export default {
  components: { connsearch, barchart, piechart },
  data() {
    return {
      time: 3,
      timeStamp: '',
      tableData: [],
      pageNum: 1,
      pageSize: 10000000,
      // pageSize: 10,
      total: 0,
      tab: false,
      tab1: true,
      intelligentDeduplication: 1,
      isautoPlay: false,
      isFullscreen: false, //跟踪全屏状态
      currentNodeLabel: '', // 当前节点的 label
      currentProgress: '', // 当前进度，例如 "10/100"
      totalNodes: 0, // 总时间节点数
      CustomerList: [],
      previewSrcList: [],
      tab2: false,
      searchform: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      formOptions: [
        {
          col: 12,
          label: "日期",
          prop: "timeRange",
          element: "el-date-picker",
          initValue: [],
          type: ""
        }
      ]
    };
  },
  computed: {
    filteredTableData() {
      return this.tableData.filter(item => this.timeStamp === item.TransTime);
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    document.addEventListener('fullscreenchange', this.handleFullscreenChange);
    document.addEventListener('webkitfullscreenchange', this.handleFullscreenChange);
    document.addEventListener('msfullscreenchange', this.handleFullscreenChange);
    this.calculateTotalNodes(); // 计算总节点数
  },
  beforeDestroy() {
    clearInterval(timer);
    document.removeEventListener('fullscreenchange', this.handleFullscreenChange);
    document.removeEventListener('webkitfullscreenchange', this.handleFullscreenChange);
    document.removeEventListener('msfullscreenchange', this.handleFullscreenChange);
  },

  methods: {
    calculateTotalNodes() {
      let allTimeNodes = [];
      this.CustomerList[0].children.forEach(dateNode => {
        if (dateNode.children && Array.isArray(dateNode.children)) {
          allTimeNodes = allTimeNodes.concat(dateNode.children);
        }
      });
      this.totalNodes = allTimeNodes.length;
    },
    getData() {
      this.GetScreenLog()
    },
    goback() {
      let query = this.$route?.query
      this.$router.replace({
        name: 'screenRecording',
        params: {
          DeviceUUID: query.DeviceUUID || '',
          DepartmentID: query.DepartmentID || '',
          StartTime: query.StartTime || '',
          EndTime: query.EndTime || '',
        }
      })
    },
    timeChange() {
      clearInterval(timer)
    },
    fullScreenAutoPlay() {
      if (!this.time || this.time < 1) {
        this.$message.info('请设置自动播放间隔，最小值1秒。')
        return
      }
      const container = this.$refs.imageContainer;
      if (container) {
        if (container.requestFullscreen) {
          container.requestFullscreen();
        } else if (container.webkitRequestFullscreen) {
          container.webkitRequestFullscreen();
        } else if (container.msRequestFullscreen) {
          container.msRequestFullscreen();
        }
        this.isFullscreen = true;
      }
      this.autoPlay();
    },
    handleFullscreenChange() {
      if (!document.fullscreenElement && !document.webkitFullscreenElement && !document.msFullscreenElement) {
        this.isFullscreen = false; // 退出全屏时设置为 false
        this.stopPlaying();
      } else {
        this.isFullscreen = true; // 进入全屏时设置为 true
      }
    },
    stopPlaying() {
      this.isautoPlay = false
      clearInterval(timer)
    },
    autoPlay() {
      if (!this.time || this.time < 1) {
        this.$message.info('请输入自动播放时间间隔,最小时间间隔为1秒');
        return;
      }
      clearInterval(timer); // 清除之前的定时器
      this.isautoPlay = true;
      let allTimeNodes = []; // 存储所有时间节点
      let totalIndex = 0; // 总索引
      // 收集所有时间节点
      this.CustomerList[0].children.forEach(dateNode => {
        if (dateNode.children && Array.isArray(dateNode.children)) {
          allTimeNodes = allTimeNodes.concat(dateNode.children);
        }
      });
      const length = allTimeNodes.length; // 总时间节点数量
      // 如果 index > 0，从指定索引开始
      if (this.index > 0 && this.index < length) {
        this.handleNodeClick(allTimeNodes[this.index]);
        totalIndex = this.index;
      } else {
        // 默认从第一个时间节点开始
        if (length > 0) {
          this.handleNodeClick(allTimeNodes[0]);
          totalIndex = 0;
        }
      }
      // 每隔 this.time 秒触发一次
      timer = setInterval(() => {
        if (totalIndex >= length) {
          clearInterval(timer);
          totalIndex = 0;
          if (length > 0) {
            this.handleNodeClick(allTimeNodes[totalIndex]);
          }
          this.$message.success('自动播放结束');
          // 退出全屏
          if (document.fullscreenElement || document.webkitFullscreenElement || document.msFullscreenElement) {
            if (document.exitFullscreen) {
              document.exitFullscreen();
            } else if (document.webkitExitFullscreen) {
              document.webkitExitFullscreen();
            } else if (document.msExitFullscreen) {
              document.msExitFullscreen();
            }
          }
          return;
        }
        this.handleNodeClick(allTimeNodes[totalIndex]);
        totalIndex++;
      }, this.time * 1000);
    },
    handleNodeClick(item) {
      if (item.level !== 3) return; // 只处理时间节点（level: 3）
      // 获取所有时间节点，用于计算全局索引
      let allTimeNodes = [];
      this.CustomerList[0].children.forEach(dateNode => {
        if (dateNode.children && Array.isArray(dateNode.children)) {
          allTimeNodes = allTimeNodes.concat(dateNode.children);
        }
      });
      // 查找当前节点在所有时间节点中的全局索引
      const globalIndex = allTimeNodes.findIndex(node => node.index === item.index);
      // 更新时间戳为完整的 TransTime
      const fullTimeStamp = this.tableData[item.index].TransTime;
      this.$nextTick(() => {
        // 更新全局索引
        this.index = globalIndex + 1;
        // 设置树状结构的当前选中项
        this.$refs.tree.setCurrentKey(item.label);
        // 更新 timeStamp 为完整时间戳
        this.timeStamp = fullTimeStamp;
        // 更新当前节点标签和进度
        this.currentNodeLabel = item.label;
        this.currentProgress = `${globalIndex + 1}/${allTimeNodes.length}`;
      });
    },
    // 获取屏幕录像
    async GetScreenLog(Distinct = 1) {
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          DeviceUUID: this.$route?.query?.DeviceUUID || '',
          DepartmentID: this.$route?.query?.DepartmentID || '',
          StartTime: this.$route?.query?.StartTime,
          EndTime: this.$route?.query?.EndTime,
          TransDate: this.$route?.query?.TransDate,
          Distinct
        }
      }
      const res = await connrequest('GetScreenLog', data)
      res.Data = res.Data || []
      const previewSrcList = []
      // 使用 Map 按日期分组时间戳
      const dateMap = new Map()
      res.Data.forEach((item, index) => {
        // 格式化时间戳
        item.TransTime = parseTime(item.TransTime, '{y}-{m}-{d} {h}:{i}:{s}')
        // 分割日期和时间
        const [date, time] = item.TransTime.split(' ')
        // 构建文件路径
        const fileName = `${window.location.protocol}//${window.location.host}/screen/${date}/${item.ResFileName}`
        item.ResFileName = fileName
        previewSrcList.push(fileName)
        // 按日期分组
        if (!dateMap.has(date)) {
          dateMap.set(date, [])
        }
        dateMap.get(date).push({ label: time, level: 3, index })
      })
      // 创建日期节点
      const dateChildren = Array.from(dateMap).map(([date, children]) => ({
        label: date,
        level: 2,
        children
      }))
      // 设置 CustomerList
      this.CustomerList = [
        {
          label: this.$route.query.Name,
          level: 1,
          children: dateChildren
        }
      ]
      // this.CustomerList = dateChildren
      this.tableData = res.Data
      this.total = res?.Paging?.TotalCount
      this.previewSrcList = previewSrcList
      // 默认选择第一个日期下的第一个时间
      if (dateChildren.length > 0 && dateChildren[0].children.length > 0) {
        this.handleNodeClick(dateChildren[0].children[0])
      }
    },
    search(val) {
      this.pageNum = 1
      this.searchform = { ...val }
      this.getData()
    },
    handleClick() {
      this.tab = !this.tab
    }
  }
};
</script>
<style lang="scss" scoped>
@import "~@/styles/variables.scss";
@import "./components/css/conncss.scss";

/* 设置垂直滚动条（如果需要水平滚动条，请添加::-webkit-scrollbar-horizontal选择器） */
::-webkit-scrollbar {
  width: 3px;
  /* 滚动条宽度 */
}

/* 滚动条轨道部分（即背景） */
::-webkit-scrollbar-track {
  background-color: #fff;
  /* 背景颜色 */
}

/* 滚动条上下两端的按钮 */
::-webkit-scrollbar-button {
  display: none;
  /* 隐藏按钮 */
}

/* 滚动条滑块部分（即滑块本身） */
::-webkit-scrollbar-thumb {
  background-color: #ccc;
  /* 滑块颜色 */
}

.lefttree {
  width: 280px;
  border: 1px solid #ebeef5;
  margin-right: 20px;
  padding: 10px;
  position: relative;
  overflow-y: auto;

  .tabclick {
    transform: rotate(-90deg);
    position: absolute;
    top: calc((100vh - 300px) / 2);
    left: -55px;
    margin-top: 20px;
  }

  ::v-deep .el-tree {
    color: #676c70;
    background-color: #ffffff;

    .tree-text {
      font-size: 14px;
      display: inline-block;
      width: 130px;
      white-space: nowrap;
      /* 禁止换行 */
      overflow: hidden;
      /* 溢出隐藏 */
      text-overflow: ellipsis;
      /* 超出部分用省略号表示 */
    }
  }

  ::v-deep.el-tree-node__content {
    &:hover {
      background-color: #cccccc;
    }
  }

  ::v-deep .el-tree-node.is-current>.el-tree-node__content {
    color: #459ffc !important;
    background-color: #f7f7f7 !important;
  }

  // ::v-deep .el-tree-node__expand-icon{
  //   position :absolute;
  //   left: 2%;
  // }
  ::v-deep .el-tree-node__label {
    padding-left: 15px;
  }
}

.playbackSettings {
  border: 1px solid #ccc;
  padding: 10px;
  margin-bottom: 10px;

  .el-input {
    margin: 0 10px;
  }

  .el-button {
    margin: 0 10px;
  }
}

.image-container {
  position: relative;
  width: 100%;
  /* 宽度占满父容器 */
  height: calc(100vh - 160px);
  /* 高度设置为 100vh - 160px */
  overflow: hidden;
  /* 防止图片溢出 */
}

.el-image {
  width: 100%;
  height: 100%;
  /* 铺满容器高度 */
  object-fit: cover;
  /* 保持比例，铺满容器，可能裁剪 */
}

/* 全屏模式下的样式（保持之前的设置） */
:fullscreen .image-container,
:-webkit-full-screen .image-container,
:-ms-fullscreen .image-container {
  background: #000;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}

:fullscreen .image-container .el-image,
:-webkit-full-screen .image-container .el-image,
:-ms-fullscreen .image-container .el-image {
  width: auto;
  height: auto;
  max-width: 100%;
  max-height: 100%;
  object-fit: contain;
  /* 全屏时保持比例，不裁剪 */
}

.fullscreen-info {
  position: absolute;
  top: 0;
  left: 50%;
  /* 将左边缘定位到屏幕的 50% */
  width: 300px;
  /* 设置固定宽度 */
  background: rgba(0, 0, 0, 0.5);
  color: white;
  padding: 10px;
  display: flex;
  justify-content: space-between;
  z-index: 1000;
  transform: translateX(-50%);
  /* 向左移动自身宽度的一半以实现居中 */
}</style>